package vip.ola.pay.batchpay.jisubatchpay;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.pay.batchpay.HttpClientUtil;
import vip.ola.pay.batchpay.Md5Util;
import vip.ola.pay.batchpay.PaysUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: dingzhiwei
 * @date: 17/12/25
 * @description:
 */
@Service
public class TestsQuickhPay {

    private static final MyLog _log = MyLog.getLog(TestsQuickhPay.class);



    public static JSONObject trans() {
        JSONObject retObj = new JSONObject();;
        String mchId ="10006";
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderId = "DS" + df.format(System.currentTimeMillis());
        Map<String,Object> map = new HashMap<>();
        map.put("merchant_id",Long.valueOf(mchId));
        map.put("remit_type",1L);
        map.put("order_no",orderId);
        map.put("device_type",1);
        map.put("payee_name", "测试");
        map.put("payee_card_no", "62258878542702222");
        map.put("payee_bank_name", "中国工商银行");
        map.put("order_amount",10000L);
        map.put("notify_url","http://159.138.11.127:8403/api/trans/notify");
        Long time = System.currentTimeMillis()/1000;
        map.put("create_time",time.intValue());
        map.put("sign",getSign(map,"a98m41be5rleppzq08vx9vlfbzrweefk"));
        map.put("user_id",UUID.randomUUID().toString());
        map.put("user_ip","159.138.11.127");
        _log.info("下单请求={}",JSONObject.toJSONString(map));
        String respData = call("https://www.sfdf.cc:10086/api/createRemit",map);
        _log.info("下单返回={}",respData);
        JSONObject jsonObject = JSONObject.parseObject(respData);
        retObj.put("transOrderId", "1234565");
        if (jsonObject != null){
            String status = jsonObject.getString("status");
            if ( "1".equals(status) ){
                retObj.put("status",1);
            }else {
                retObj.put("status",3);
                retObj.put("channelErrCode", status);
                retObj.put("channelErrCode", jsonObject.getString("text"));
            }
        }else {
            retObj.put("status",3);
        }
        return  retObj;
    }

    private static String getSign(Map<String,Object> object, String privateKey) {
        Long merchantId = (Long) object.get("merchant_id");
        String orderNo = (String) object.get("order_no");
        Long payType = (Long) object.get("remit_type");
        Long orderAmount = (Long) object.get("order_amount");
        String notifyUrl = (String) object.get("notify_url");
        Integer createTime = (Integer) object.get("create_time");
        StringBuffer sb = new StringBuffer();
        sb.append(merchantId).append(orderNo).append(payType).append(orderAmount).append(notifyUrl).append(createTime).append(privateKey);
        return PayDigestUtil.md5((sb.toString()),"UTF-8");
    }


    public static String call(String url, Map param) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 响应模型
        CloseableHttpResponse response = null;
        String responseContext = null;
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(param), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                responseContext = EntityUtils.toString(responseEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContext;
    }



    public static void main (String args[]){
////        trans();
//        String signs="FtlR5eqZ4PaZR3vWSjRhd+1VFJhOZ8S6ceRnhhY+5n/v9UEcOw90CRU0kGZmvZTui687s90hDIb5OXqNBFK4eYZCAXUH8Yje1AMbsupKKVDYBCd4Dwlt0JcGd9PpJM7RtVj9GcK2APxe9ke//uZzZbA/Tc+E01UqsPIcK4v4KwE=";
//        TreeMap<String, String> jsonObject = new TreeMap<String, String>();
//        jsonObject.put("merId","202110151");
//        jsonObject.put("orderId","DS20211023183852");
//        jsonObject.put("nonceStr","9Mvyh6UsqEteCgcKWw1kH8jPoGIX2rYT");
////        jsonObject.put("sign","FtlR5eqZ4PaZR3vWSjRhd+1VFJhOZ8S6ceRnhhY+5n\\/v9UEcOw90CRU0kGZmvZTui687s90hDIb5OXqNBFK4eYZCAXUH8Yje1AMbsupKKVDYBCd4Dwlt0JcGd9PpJM7RtVj9GcK2APxe9ke\\/\\/uZzZbA\\/Tc+E01UqsPIcK4v4KwE=");
//        StringBuffer paramstr = new StringBuffer();
//        for (String pkey : jsonObject.keySet()) {
//            String pvalue = jsonObject.get(pkey);
//            if (pvalue != null && pvalue != "") {
//                paramstr.append(pkey + "=" + pvalue + "&");
//            }
//        }
//        String paramsrc = paramstr.substring(0, paramstr.length() - 1);
//        String sign = sign(paramsrc);
//        try{
//         Boolean flag=  RSAUtils.verify(sign.getBytes("UTF-8"), PaysUtil.pubkey,signs);
//            System.out.println(flag);
//       }catch (Exception e){
//           System.out.println(1111);
//       }

//        query();
    //    System.out.println(MD5Util.string2MD5("123456"));
//        String url ="http://payapi.gb666.net/Notify/GetNotify?income=8950&payOrderId=DS12021102414294428299&amount=10000&mchId=9326&productId=10001&paySuccTime=1635057091000&sign=80A0863AB2FC09EA60F1556212EE46F3&channelOrderNo=&backType=2&param1=&param2=&outTradeNo=2021103222321958021&status=2";
//      String resp=  PayUtil.call4Post(url);
//        System.out.println(resp);
//        trans();
//        String mchId= "9295";
//        String mchOrderNo="SF20250308001344W";
//        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
//        String reqestTime = df.format(System.currentTimeMillis());
//        System.out.println(reqestTime);
//        Map<String,Object> map = new HashMap<>();
//        map.put("mchId",mchId);
//        map.put("reqTime",reqestTime);
//        map.put("mchOrderNo",mchOrderNo);
//        System.out.println(PayDigestUtil.getSign(map, "KHX31BZUIMRIXNFLNALIDO2IFV7UAQVUHYPZBDOTZVHYRM8DR2TQSIY5PHBT6IAOSYZQMUBMH1NLWXJINF30YFOIJMJWT9RVXXBIQYZZGSPBM4YQNZUXV0KQXW8THGNM"));
//        Calendar cal = Calendar.getInstance();
//        cal.add(Calendar.DATE, -10);
//        cal.set(Calendar.DAY_OF_MONTH, 1);
//        System.out.println(cal.getTime());
        String tmp ="{\"Data\":[{\"CurrencyId\":1,\"CurrencyName\":\"人民币\",\"Balance\":0.0}],\"Code\":0,\"Message\":\"\"}";
        JSONObject jsonObject = JSONObject.parseObject(tmp);
        if (jsonObject != null) {
            String code = jsonObject.getString("Code");
            if ("0".equals(code)) {
                String totalAmt = jsonObject.getJSONArray("Data").getJSONObject(0).getString("Balance");
                JSONObject result = new JSONObject();
                result.put("retCode", "SUCCESS");
                result.put("cashBalance", totalAmt);
                System.out.println(result.toJSONString());


            }
        }
    }


}
